/*
参数说明：
  // errorHandel 1:退出登录 2:弹框提示 3:重连 4:抛出异常
  // retry：重连次数, retryDelay：重连每次间隔事件ms

*/

import Vue from 'vue'
import { Toast } from 'vant'
import baseApi from './baseApi'
Vue.use(Toast)

// 错误处理 ——errorHandel 1:退出登录 2:弹框提示 3:重连 4:抛出异常
export function fnHandelError(errType, error) {
  let statusText
  // let status, code

  var {
    config,
    config: { errorHandel = {} } = {}
  } = error || {};
  let { type = 2 } = errorHandel

  if (errType === 'httpError') {
    statusText = error.request && error.request.statusText || '数据更新异常，请稍后再试！'
    // status = error.request.status
  } else if (error.data) {
    statusText = error.data.message
    // status = error.status
    // code = error.data.code
  } else {
    statusText = '数据更新异常，请稍后再试！'
  }
  switch (type) {
    case 1:
      Toast({
        message: '跳转到登录页面',
        type: 'fail',
        duration: 3 * 1000,
        onClose: () => {}
      })
      break
    case 2:
      Toast({
        message: statusText,
        type: 'fail',
        duration: 3 * 1000
      })
      break
    case 3:
      fnReTry.call(this, config) //this就是service
      break
    default:
  }
}

// 重连 retry：次数, retryDelay：每次间隔事件ms
//计数小于retry，延时retryDelay，然后调用service继续请求
function fnReTry(config) {
  let {
    errorHandel: { retry, retryDelay }
  } = config
  config.__retryCount = config.__retryCount || 0

  config.__retryCount += 1

  if (config.__retryCount <= retry) {
    let backoff = new Promise(function(resolve) {
      let timer = null
      timer = setTimeout(function() {
        resolve()
        clearTimeout(timer)
      }, retryDelay || 30)
    })

    backoff.then(() => {
      let { baseURL } = baseApi
      config.url = config.url.replace(baseURL, '')
      return this(config)
    })
  }
}
